/**
 * Copyright 2010 Jake Jackson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jake.nb.ext.ant.hints.impl.dependserrors;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.jake.nb.ext.ant.hints.AntHint;
import org.jake.nb.ext.ant.hints.Configuration;
import org.jake.nb.ext.ant.hints.Paths;
import org.jake.nb.ext.ant.hints.SpanContainer;
import org.jake.nb.ext.ant.parser.DocumentUtilities;
import org.jake.nb.ext.ant.parser.Span;
import org.jake.nb.ext.ant.parser.Spans;
import org.netbeans.modules.editor.NbEditorUtilities;
import org.netbeans.spi.editor.hints.ChangeInfo;
import org.netbeans.spi.editor.hints.ErrorDescription;
import org.netbeans.spi.editor.hints.ErrorDescriptionFactory;
import org.netbeans.spi.editor.hints.Fix;
import org.netbeans.spi.editor.hints.Severity;
import org.openide.text.Line;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;

/**
 * Class to indicate a duplicate entry in depends attribute, like depends="clean, clean". Provides a fix.
 * XXX: provide a fix to replace the duplicate call by the full qualified call if available
 * @author JakeJ
 */
@ServiceProvider(service = AntHint.class, path = "org-jake-nb-ext-ant-hints")
public class DuplicateEntryInDepends implements AntHint {

  private Configuration configuration;

  public DuplicateEntryInDepends() {
    configuration = new Configuration(DuplicateEntryInDepends.class.getCanonicalName(),
            "Duplicate call in depends",
            "Checks a depends clause contains multiple calls to the same target. This is not wrong at all, as ANT will"
            + " ignore this anyway, but it's harder to read and maintain.",
            true,
            Severity.HINT, Paths.DEPENDS);
  }

  @Override
  public Collection<ErrorDescription> getErrors(final SpanContainer spanContainer) {
    final Collection<ErrorDescription> errors = new HashSet<ErrorDescription>();
    final Spans dependSpans = spanContainer.getDependSpans();
    for (final Span span : dependSpans.getSpans()) {
      final String fullAttribute = getDepends(span);
      if (fullAttribute.length() > 0) {
        final int firstQuote = fullAttribute.indexOf('"') + 1; // NOI18N
        final int lastQuote = fullAttribute.indexOf('"', firstQuote); // NOI18N
        final String dependsClause = fullAttribute.substring(firstQuote, lastQuote);
        if (hasDuplicate(dependsClause)) {
          errors.add(createError(spanContainer.getDocument(), span, dependsClause));
        }
      }
    }

    return errors;
  }

  @Override
  public Configuration getConfiguration() {
    return configuration;
  }

  /**
   * Gets the full string of the depends attribute, e.g. depends="a, b", but only in case there are multiple entries
   * @param span
   * @return
   */
  private String getDepends(final Span span) {
    String text = null;
    try {
      text = span.getDocument().getText(span.getStart(), span.getLength() + 1);
    } catch (BadLocationException ex) {
      text = ""; // NOI18N
    }

    // the depends clause needs to be checked if and only there are two entries
    if (text.length() > 0 && !text.contains(",")) { // NOI18N
      text = ""; // NOI18N
    }

    return text;
  }

  private ErrorDescription createError(final Document document, final Span span, final String dependsClause) {
    final Fix dupFix = new RemoveDuplicatesEntriesForDependsFix(document, span, dependsClause, NbBundle.getMessage(this.getClass(), "FIX_DUPLENTRIES")); // NOI18N

    final List<Fix> fixes = new ArrayList<Fix>();
    fixes.add(dupFix);

    final Line line = NbEditorUtilities.getLine(document, span.getStart(), true);
    final ErrorDescription desc = ErrorDescriptionFactory.createErrorDescription(configuration.getSeverity(), NbBundle.getMessage(this.getClass(), "DESC_ERR_DUPLENTRIES"), fixes, document,
            line.getLineNumber() + 1);
    return desc;
  }

  private boolean hasDuplicate(final String dependsClause) {
    boolean ret = false;
    final Collection<String> used = new HashSet<String>();
    StringTokenizer tokenizer = new StringTokenizer(dependsClause, ","); // NOI18N
    while (tokenizer.hasMoreTokens()) {
      final String nextToken = tokenizer.nextToken().trim();
      if (used.contains(nextToken)) {
        // skip the first occurence
        ret = true;
        break;
      }
      used.add(nextToken);
    }
    return ret;
  }

  private static class RemoveDuplicatesEntriesForDependsFix implements Fix {

    private final Span span;
    private final Document document;
    private final String dependsValue;
    private final String text;

    RemoveDuplicatesEntriesForDependsFix(final Document document, final Span span, final String dependsValue, final String text) {
      this.document = document;
      this.span = span;
      this.dependsValue = dependsValue;
      this.text = text;
    }

    @Override
    public String getText() {
      return text;
    }

    @Override
    public ChangeInfo implement() throws Exception {
      ChangeInfo info = new ChangeInfo();
      final String fullText = document.getText(span.getStart(), span.getLength() + 1);
      String newValue = fullText.substring(0, fullText.indexOf(dependsValue));
      Collection<String> alreadyFound = new HashSet<String>();
      final StringTokenizer tokenizer = new StringTokenizer(dependsValue, ","); // NOI18N
      boolean first = true;
      while (tokenizer.hasMoreTokens()) {
        final String nextToken = tokenizer.nextToken();
        final String trimmed = nextToken.trim();
        if (!alreadyFound.contains(trimmed)) {
          if (!first) {
            newValue += ","; // NOI18N
          }
          first = false;
          newValue += nextToken;
        }
        alreadyFound.add(trimmed);
      }
      if (!newValue.endsWith("\"")) { // NOI18N
        newValue += "\""; // NOI18N
      }
      document.remove(span.getStart(), span.getLength() + 1);
      document.insertString(span.getStart(), newValue, null);
      DocumentUtilities.save(document);
      return info;
    }
  }
}
